using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SqlTools.SchemaReader
{
	public class DbCollection<T> : List<T> where T : DbObject, new()
	{
		public T this[string name]
		{
			get
			{
				for ( int i = 0; i < this.Count; i++ )
				{
					if ( this[i].Name == name )
						return this[i];
				}
				return null;
			}
		}

		public T RetrieveByID(int ID)
		{
			for ( int i = 0; i < this.Count; i++ )
			{
				if ( this[i].ID == ID )
					return this[i];
			}

			return null;
		}

		/// <summary>
		/// Saves the schema represented by this object to XML.
		/// </summary>
		/// <param name="doc">An existing XmlDocument with a defined document element</param>
		/// <param name="xmlParent">The parent element that will contain this objects
		/// schema</param>
		public virtual void SaveXml(XmlDocument doc, XmlNode xmlParent)
		{
			XmlElement xmlColl = CreateXmlElement(doc, xmlParent);
            if(xmlColl != null)
			foreach ( T obj in this )
			{
                // TODOS GPC
                if(obj != null)
				obj.SaveXml(doc, xmlColl);
			}
		}

		/// <summary>
		/// Creates the default xml element for this type
		/// </summary>
		/// <param name="doc">An existing XmlDocument with a defined document element</param>
		/// <param name="parent">The parent element that will contain this object</param>
		/// <returns>The Xml Element that represents this object.</returns>
		public virtual XmlElement CreateXmlElement(XmlDocument doc, XmlNode parent)
		{
			Type type = typeof(T);
			string collName = type.Name + "Collection";

			XmlElement xmlRoot = doc.CreateElement(collName);

			parent.AppendChild(xmlRoot);

			return xmlRoot;
		}

		public virtual void LoadXml(XmlElement el, Database db)
		{
			string nodeName = typeof(T).Name;

			foreach ( XmlNode node in el.ChildNodes )
			{
				if ( node.NodeType == XmlNodeType.Element )
				{
					XmlElement xmlEl = node as XmlElement;

					if ( xmlEl.Name == nodeName )
					{
						T obj = new T();

						this.Add(obj);

						obj.LoadXml(xmlEl, db);
					}
				}
			}
		}

		public string XmlElementName
		{
			get { return typeof(T).Name + "Collection"; }
		}
	}
}
